#include "binddevice.h"
#include "ui_binddevice.h"
#include <QBluetoothAddress>
#include <QBluetoothLocalDevice>
#include <QDebug>
#include <qfiledevice.h>
#include <qmessagebox.h>
#include <qserialportinfo.h>
#include <Utils/settingmanager.h>

BindDevice::BindDevice(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::BindDevice)
{
    ui->setupUi(this);
    ui->tabWidget_bindDevices->setCurrentIndex(0);
    checkBluetooth();
    connect(&m_agent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)), this, SLOT(onDeviceDiscovered(QBluetoothDeviceInfo)));
    connect(&m_agent, SIGNAL(scanFinished()), this, SLOT(onScanFinished()));
    initSerialPort();
    isClear=false;
    isBind=false;
    initSettings();
}

BindDevice::~BindDevice()
{
    delete serialPort;
    delete ui;
}
void BindDevice::on_pb_close_clicked()
{
    if(serialPort->isOpen())
        serialPort->close();

    this->close();
}
/**
 * 检测本机是否支持蓝牙
 * @brief BindDevice::checkBluetooth
 */
void BindDevice::checkBluetooth() {
    QList<QBluetoothHostInfo> hosts = QBluetoothLocalDevice::allDevices();
    if (hosts.isEmpty()) {
        ui->label_blelocal->setText("本地没有发现可支持的蓝牙，您可以手动输入需要绑定的设备mac地址");
        ui->label_bind_scanInfo->setText("请您手动输入设备的Mac地址，如AABBCCDDEEFF,具体名称可通过手机蓝牙扫描发现。");
        qDebug() << "No Bluetooth devices found";
    } else {
        qDebug() << "Bluetooth devices found:";
        ui->label_blelocal->setText("发现可支持的蓝牙，您可以通过蓝牙搜索的方式绑定所需设备的mac地址，蓝牙搜索绑定之前，请您先将电脑端的USB适配器拔下来。");
        ui->label_bind_scanInfo->setText("请将需要绑定的设备开机，然后点击扫描按钮，查询设备Mac地址。");
        for (const QBluetoothHostInfo &host : hosts) {
            qDebug() << "Name:" << host.name() << "Address:" << host.address().toString();
        }
    }


}

void BindDevice::initSettings()
{
    SettingManager BindD("bindDevice");
    ui->lineEdit_ecgMac->setText(BindD.getValue<QString>("ecgMac", ""));
    ui->lineEdit_eegMac->setText(BindD.getValue<QString>("eegMac", ""));
    ui->lineEdit_OxMac->setText(BindD.getValue<QString>("OxMac", ""));
    ui->lineEdit_emgMac->setText(BindD.getValue<QString>("emgMac", ""));

    ui->lineEdit_ecgNo->setText(BindD.getValue<QString>("ecgNo", ""));
    ui->lineEdit_eegNo->setText(BindD.getValue<QString>("eegNo", ""));
    ui->lineEdit_OxNo->setText(BindD.getValue<QString>("OxNo", ""));
    ui->lineEdit_emgNo->setText(BindD.getValue<QString>("emgNo", ""));
}

void BindDevice::onDeviceDiscovered(const QBluetoothDeviceInfo &info)
{
    ui->label_bind_scanInfo->setText(info.name()+"-"+info.address().toString());
    if(info.name().contains("QX-EEG-PLUS")){
        QString mac=info.address().toString();
        mac.remove(QChar(':'), Qt::CaseInsensitive);
        ui->lineEdit_eegMac->setText(mac);

    }
    if(info.name().contains("QX-ECG-HOLTER")){
        QString mac=info.address().toString();
        mac.remove(QChar(':'), Qt::CaseInsensitive);
        ui->lineEdit_ecgMac->setText(mac);
    }
    if(info.name().contains("QX-HRV")){
        QString mac=info.address().toString();
        mac.remove(QChar(':'), Qt::CaseInsensitive);
        ui->lineEdit_OxMac->setText(mac);
    }
    if(info.name().contains("QX-EMG")){
        QString mac=info.address().toString();
        mac.remove(QChar(':'), Qt::CaseInsensitive);
        ui->lineEdit_emgMac->setText(mac);
    }

}
void BindDevice::onScanFinished()
{
    ui->label_bind_scanInfo->setText("扫描完成，如未发现所需设备，请您重新扫描。如一直未发现所需设备，请查看设备是否开机，\r\n如发现所有所需设备，请插入USB适配器绑定设备");
    ui->pb_scan->setText("扫描");
}
void BindDevice::on_pb_next_clicked()
{
    ui->tabWidget_bindDevices->setCurrentIndex(1);
}


void BindDevice::on_pb_scan_clicked()
{
    m_agent.startScanDevice(12000);
    ui->pb_scan->setText("扫描中。。");
}


void BindDevice::on_pb_RefreshSerial_clicked()
{
    qDebug()<<"on_pb_RefreshSerial_clicked";
    refresh_serial();
}
void BindDevice::initSerialPort()
{
    serialPort=new QSerialPort();
    connect(serialPort,SIGNAL(readyRead()),this,SLOT(readComDataSlot()));
}

void BindDevice::refresh_serial()
{
    QStringList comname; //活动串口表
    comname.clear();
    ui->comboBox_serialPort->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        if(info.productIdentifier()==0x6001 && info.vendorIdentifier()==0x0403){
            comname.append(info.portName());
        }
    }
    ui->comboBox_serialPort->addItems(comname);
}
void BindDevice::on_pb_OpenSerial_clicked()
{
    if(ui->pb_OpenSerial->text()=="打开串口"){
        QString portName=ui->comboBox_serialPort->currentText();
        if(portName.contains("COM")){
            serialPort->setPortName(portName);
            serialPort->setBaudRate(460800);
            if(serialPort->open(QFileDevice::ReadWrite))
            {
                ui->label_serialPortState->setText("串口打开成功");
                ui->pb_OpenSerial->setText("关闭串口");
                SettingManager SerialInfo("SerialInfo");
                SerialInfo.setValue("spName", portName);

            }else{
                ui->label_serialPortState->setText("串口打开失败");
            }
        }else{
            QMessageBox::about(this,"温馨提醒","请先将USB适配器插入电脑U口刷新");
        }
    }else{
        serialPort->close();
        ui->label_serialPortState->setText("串口关闭");
        ui->pb_OpenSerial->setText("打开串口");
    }
}
void BindDevice::on_pb_clearDevice_clicked()
{
    if(serialPort->isOpen())
    {
        isClear=true;
        qDebug()<<"serialPort_CLEAR";
        QString order="AT+CLEAR\r\n";
        serialPort->write(order.toUtf8());

    }else{
        QMessageBox::about(this,"温馨提醒","未打开串口");
    }
}

void BindDevice::readComDataSlot()
{
    QByteArray readComData = serialPort->readAll();
    if(isClear){
        ui->label_serialPortState->setText("设备清除："+QString(readComData));
        isClear=false;
    }
    if(isBind){
        ui->label_serialPortState->setText("设备绑定："+QString(readComData));
        isBind=false;
        qDebug()<<"ecgMac"<<":setValue"<<ui->lineEdit_ecgMac->text();
        SettingManager BindD("bindDevice");
        BindD.setValue("ecgMac",ui->lineEdit_ecgMac->text());
        BindD.setValue("eegMac",ui->lineEdit_eegMac->text());
        BindD.setValue("OxMac",ui->lineEdit_OxMac->text());
        BindD.setValue("emgMac",ui->lineEdit_emgMac->text());
        BindD.setValue("ecgNo",ui->lineEdit_ecgNo->text());
        BindD.setValue("eegNo",ui->lineEdit_eegNo->text());
        BindD.setValue("OxNo",ui->lineEdit_OxNo->text());
        BindD.setValue("emgNo",ui->lineEdit_emgNo->text());

    }
}

void BindDevice::on_pb_bindDevice_clicked()
{
    QString dualEEGMac=ui->lineEdit_eegMac->text();
    QString ecgMac=ui->lineEdit_ecgMac->text();
    QString emgMac=ui->lineEdit_emgMac->text();
    QString oxMac=ui->lineEdit_OxMac->text();
    if(dualEEGMac.length()==12 || ecgMac.length()==12 || emgMac.length()==12 || oxMac.length()==12){
        if(serialPort->isOpen())
        {
            isBind=true;
            QString order="AT+SetMac"+dualEEGMac+ecgMac+"\r\n";
            serialPort->write(order.toUtf8());
        }else{
            QMessageBox::about(this,"温馨提醒","未打开串口");
        }
    }else{
        QMessageBox::about(this,"温馨提醒","请至少绑定一个设备");
    }

}

void BindDevice::on_pb_reset_clicked()
{
    ui->lineEdit_ecgMac->setText("");
    ui->lineEdit_eegMac->setText("");
    ui->lineEdit_OxMac->setText("");
    ui->lineEdit_emgMac->setText("");

    ui->lineEdit_ecgNo->setText("");
    ui->lineEdit_eegNo->setText("");
    ui->lineEdit_OxNo->setText("");
    ui->lineEdit_emgNo->setText("");
}

